package com.bilibili.juc.cf.one;

import cn.hutool.core.util.RandomUtil;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class FutureWhenCompleteTwoTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<String> orgFuture = CompletableFuture.supplyAsync(
                ()->{
                    System.out.println(" supplyAsync 当前线程名称：" + Thread.currentThread().getName());
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    int count = RandomUtil.randomInt(1, 10);
                    System.out.println("随机数为: " + count);
                    if (count < 7){
                        throw new RuntimeException("第一个任务抛出了异常");
                    }
                    return "捡田螺的小男孩";
                }
        );

        /*
orgFuture.whenComplete 方法任务：无论orgFuture是否正常都会执行whenComplete方法，
当orgFuture产生异常时throwable不为null，执行完whenComplete方法后就会抛出异常终止程序的运行
才当orgFuture正常时throwable为null，执行完whenComplete方法后就会继续运行程序的后面的任务
 */
        CompletableFuture<String> rstFuture = orgFuture.whenComplete((a, throwable) -> {
            System.out.println(" whenComplete 当前线程名称：" + Thread.currentThread().getName());
            if (Objects.nonNull(throwable)){//异常情况
                System.out.println("!!!!!!!!!!! 上一个任务出现了异常==>> " + throwable.getMessage());
            }else { //正常情况
                System.out.println("上个任务执行完啦，还把结果为: \"" + a + "\" 传过来");
                if ("捡田螺的小男孩".equals(a)) {
                    System.out.println("666");
                }
                System.out.println("233333");
            }
        });

        System.out.println(rstFuture.get());
        for (int i = 0 ; i < 5;i++){
            System.out.println(" 主程序正在执行其它的任务"+i);
            TimeUnit.SECONDS.sleep(1);
        }
    }
}
//输出
/*
当前线程名称：ForkJoinPool.commonPool-worker-1
当前线程名称：ForkJoinPool.commonPool-worker-1
上个任务执行完啦，还把捡田螺的小男孩传过来
666
233333
捡田螺的小男孩
* */